//
//  AddressSelectVC.m
//  WoWeiRenRenOC
//
//  Created by 姜伟 on 2020/3/19.
//  Copyright © 2020 姜孟东. All rights reserved.
//

#import "AddressSelectVC.h"
#import "AddressSelectHeader.h"
#import "ChooseLocationView.h"
#import "CitiesDataTool.h"
#import <BMKLocationKit/BMKLocationComponent.h>

@interface AddressSelectVC () <AddressSelectHeaderDelegate, NSURLSessionDelegate, UIGestureRecognizerDelegate, BMKLocationAuthDelegate, BMKLocationManagerDelegate>

@property (nonatomic, strong) AddressSelectHeader *header;

@property (nonatomic, strong) ChooseLocationView *chooseLocationView;
@property (nonatomic, strong) UIView  *cover;

@property (nonatomic, copy) NSString *appKey;
@property (nonatomic, copy) NSString *webAppKey;

@property (nonatomic, strong) BMKLocationManager *locationManager;

@property (assign, nonatomic)BOOL isRequset;
@end

@implementation AddressSelectVC

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.title = @"选择详细地址";
    self.appKey = @"Y8iBc82CPB8XtRcuYMIjxRFVz2KcfuXW";
    self.webAppKey = @"4V320aH9TSyEHG6BREEBfPkOXiH3HMlm";
    
    [self setupLocationManager];
    [self creatTableViewWithCellIdentity:@""];
    self.tableView.backgroundColor = [UIColor whiteColor];
    self.tableView.rowHeight = 40;
    self.tableView.frame = CGRectMake(0, 0, kScreenW, kScreenH);
    self.tableView.tableHeaderView = self.header;
    self.header.delegate = self;
}
- (void)setupLocationManager
{
    [self.header.cityButton setTitle:@"定位中." forState:UIControlStateNormal];
    
    [[BMKLocationAuth sharedInstance] checkPermisionWithKey:self.appKey authDelegate:self];
    
    //开始定位
    WeakSelf(ws)
    [self.locationManager requestLocationWithReGeocode:YES withNetworkState:YES completionBlock:^(BMKLocation * _Nullable location, BMKLocationNetworkState state, NSError * _Nullable error) {
        if (error) {
            
            [ws.header.cityButton setTitle:@"定位失败" forState:UIControlStateNormal];
        }
        else {
            [ws.header.cityButton setTitle:location.rgcData.city forState:UIControlStateNormal];
        }   
    }];
}

- (void)headerCityButtonClick:(UIButton *)cityBtn
{
    [self.view endEditing:YES];
    
    [UIView animateWithDuration:0.25 animations:^{
        self.cover.hidden = !self.cover.hidden;
        self.chooseLocationView.hidden = self.cover.hidden;
        if (self.cover.hidden) {
            self.chooseLocationView.y = kScreenH;
        }
        else {
            self.chooseLocationView.y = kScreenH - 350;
        }
    }];
}

- (void)headerSearchButtonClick:(NSString *)searchText
{
   
    
    if ([CommonTTool isStrNull:searchText]) {
        SVP(@"请输入需要搜索的地址");
        return;
    }
    if (self.isRequset) {
        SVP(@"您的操作太频繁了，请稍后重试");
        return;
    }
    
    
    
//     //GET请求
    NSString *region = self.header.cityButton.currentTitle;
    if ([region hasPrefix:@"定位"]) {
        region = @"全国";
    }
    else if ([region hasSuffix:@"市"]){
        region = [region substringToIndex:region.length-1];
    }
    
//    NSString *url = [NSString stringWithFormat:@"http://api.map.baidu.com/place/v2/search?query=%@&region=%@&output=json&scope=2&ak=%@", searchText, region, self.webAppKey];
//    url = [url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    //url = [url stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
    NSDictionary *dict = @{@"query":[NSString stringWithFormat:@"%%%@",searchText],@"region":region,@"output":@"json",@"scope":@"2",@"ak":self.webAppKey};
    
    SVPShowInternetWaiting
    [[NetRequestTool manager] GET:@"http://api.map.baidu.com/place/v2/search" parameters:dict progress:^(NSProgress * _Nonnull downloadProgress) {
            
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        //[NSThread sleepForTimeInterval:1.0];
        SVPDismiss
        self.isRequset = YES;
        [self performSelector:@selector(delayMethod) withObject:self afterDelay:1.5];

        
        NSDictionary *returnDic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
        self.dataArray = [NSMutableArray array];
        for (NSDictionary *dict in returnDic[@"results"]) {
            NSString *address = dict[@"name"];
            if (![CommonTTool isBlankString:address]) {
                [self.dataArray addObject:address];
            }
        }
        dispatch_async(dispatch_get_main_queue(), ^{
               [self.tableView reloadData];
        });
        
        
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"%@", error);
        SVP(@"搜索失败");
    }];
}

- (void)delayMethod {
    
    self.isRequset = NO;
    
    
}
    

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    if (cell==nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell"];
        cell.textLabel.font = kFont(14.0);
        cell.textLabel.textColor = FloatColor(0x11100D);
    }
    cell.textLabel.text = self.dataArray[indexPath.row];
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
        
    NSString *addressStr = self.dataArray[indexPath.row];
//    if (![self.header.cityButton.currentTitle hasPrefix:@"定位"]) {
//        addressStr = [NSString stringWithFormat:@"%@%@", self.header.cityButton.currentTitle, addressStr];
//    }
    if (self.selectFinish) {
        self.selectFinish(addressStr);
    }
    [self.navigationController popViewControllerAnimated:YES];
}

- (BOOL)gestureRecognizerShouldBegin:(UIGestureRecognizer *)gestureRecognizer
{
    CGPoint point = [gestureRecognizer locationInView:gestureRecognizer.view];
    if (CGRectContainsPoint(_chooseLocationView.frame, point)){
        return NO;
    }
    return YES;
}

- (AddressSelectHeader *)header
{
    if (!_header) {
        _header = [[NSBundle mainBundle] loadNibNamed:@"AddressSelectHeader" owner:self options:nil].lastObject;
        _header.frame = CGRectMake(0, 0, kScreenW, 60);
        [_header.searchBtn setUi];
        [_header.searchBtn addTarget:self action:@selector(searchAddress) forControlEvents:UIControlEventTouchUpInside];
        _header.searchBtn.layer.cornerRadius = 15;
    }
    return _header;
}

- (void)searchAddress {
    
    [self headerSearchButtonClick:self.header.searchText.text];

}

- (ChooseLocationView *)chooseLocationView{
    
    if (!_chooseLocationView) {
       _chooseLocationView = [[ChooseLocationView alloc]initWithFrame:CGRectMake(0, kScreenH, kScreenW, 350)];
    }
    return _chooseLocationView;
}

- (UIView *)cover{

    if (!_cover) {
        [[CitiesDataTool sharedManager] requestGetData];
        _cover = [[UIView alloc]initWithFrame:[UIScreen mainScreen].bounds];
        _cover.backgroundColor = [UIColor colorWithWhite:0 alpha:0.2];
        _cover.hidden = YES;
        [self.view addSubview:_cover];
        
        UITapGestureRecognizer * tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapCover:)];
        [_cover addGestureRecognizer:tap];
        tap.delegate = self;
        
        [_cover addSubview:self.chooseLocationView];
        __weak typeof (self) weakSelf = self;
        _chooseLocationView.chooseFinish = ^{
            NSLog(@"%@", weakSelf.chooseLocationView.address);
            if (![CommonTTool isBlankString:weakSelf.chooseLocationView.city]) {
                [weakSelf.header.cityButton setTitle:weakSelf.chooseLocationView.city forState:UIControlStateNormal];
            }
            [weakSelf hiddenCoverAnimate];
        };
    }
    return _cover;
}

- (void)tapCover:(UITapGestureRecognizer *)tap{
    if (_chooseLocationView.chooseFinish) {
         _chooseLocationView.chooseFinish();
    }
}

- (void)hiddenCoverAnimate
{
    [UIView animateWithDuration:0.25 animations:^{
        self.chooseLocationView.y = kScreenH;
    } completion:^(BOOL finished) {
        self.cover.hidden = YES;
    }];
}

- (BMKLocationManager *)locationManager
{
    if (!_locationManager) {
        //初始化实例
        _locationManager = [[BMKLocationManager alloc] init];
        //设置delegate
        _locationManager.delegate = self;
        //设置返回位置的坐标系类型
        _locationManager.coordinateType = BMKLocationCoordinateTypeBMK09LL;
        //设置距离过滤参数
        _locationManager.distanceFilter = kCLDistanceFilterNone;
        //设置预期精度参数
        _locationManager.desiredAccuracy = kCLLocationAccuracyBest;
        //设置应用位置类型
        _locationManager.activityType = CLActivityTypeAutomotiveNavigation;
        //设置是否自动停止位置更新
        _locationManager.pausesLocationUpdatesAutomatically = YES;
        //设置位置获取超时时间
        _locationManager.locationTimeout = 10;
        //设置获取地址信息超时时间
        _locationManager.reGeocodeTimeout = 10;
    }
    return _locationManager;
}

- (void)dealloc
{
    
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    self.locationManager = nil;
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
